{"cells":[{"cell_type":"markdown","metadata":{"_id":"92CD1AE3449F46E7AD64CC7DBC687AC8","id":"9FCE07AFBA0548DDA16BAF0EFF680EB3","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["# <center>高级心理统计 (Advanced Statistics in Psych Sci) </center>  \n","## <center>《贝叶斯统计及其在Python中的实现》 (Bayesian inference with Python) </center>  \n","## <center>Instructor： 胡传鹏（博士）(Dr. Hu Chuan-Peng) </center>  \n","### <center>南京师范大学心理学院 (School of Psychology, Nanjing Normal University)  </center>"]},{"cell_type":"markdown","metadata":{"_id":"7D2B3466FE33434C80F2AC8D4245B212","id":"800150EB466D4814859CB1EDEC868E77","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["## Outlines  \n","### 1. 为什么要学习本课程 [Why Bayesia inference]  \n","### 2. 本课程的内容将是什么 [What is the syllabus]  \n","###  3. 如何学好这门课[How can I learn this course well]"]},{"cell_type":"markdown","metadata":{"_id":"0A6BA84DB12B4911AC1593844A883E46","id":"EF04F4770D46465EB3C11AF156BF5BCE","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["##  0. 贝叶斯统计课程选课概况  \n","- 学生身份  \n","\n","![Image Name](https://cdn.kesci.com/upload/sjboycorpy.png?imageView2/0/w/960/h/960)  \n","\n","- 教育程度  \n","\n","\n","![Image Name](https://cdn.kesci.com/upload/sjbp057ve3.png?imageView2/0/w/960/h/960)  \n","\n","\n","- 专业领域  \n","\n","![Image Name](https://cdn.kesci.com/upload/sjbor7adly.png?imageView2/0/w/960/h/960)  \n","  \n","\n","- 编程经验  \n","\n","![Image Name](https://cdn.kesci.com/upload/sjbp0nk57u.png?imageView2/0/w/960/h/960)  \n","\n"]},{"cell_type":"markdown","metadata":{"_id":"9C4430B160204A82B50A00C81B6EAFE1","id":"A636A8262AEF4580AB91E8539778B2E8","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### <center>总结：贝叶斯统计线上课程吸引了众多高学历在读学生，但学员普遍缺乏编程基础。<center>"]},{"cell_type":"markdown","metadata":{"_id":"96832098FFA14472A124F741A4C8568F","id":"4B4E9D2B208E43A5A7F70EFCC7B15EB0","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["<center><span style=\"font-size: 72px;\">Part 1: Why Bayesian statistics</span></center>"]},{"cell_type":"markdown","metadata":{"_id":"1A6F87B0CE8B4364A61C4BD3D45FB35F","id":"F9A955D742BE454183C967DC155820A3","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["<center> <span style=\"font-size: 56px;\">研究人类心理与行为的规律，  \n","\t容易吗？  </center>  \n","\t"]},{"cell_type":"markdown","metadata":{"_id":"8FF57FB9DE764F908CF5BEBF7F0AEC99","id":"2233E778013A4CEB97553A29998FC2FA","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["##  1.  为什么要学习本课程 (Why Bayesia inference)  \n","\n","### 1.1  为什么心理学需要更好的方法 (Why does psychological science need better methods?)  \n","\n","#### 原因1:  人类认知与行为本身的复杂性"]},{"cell_type":"markdown","metadata":{"_id":"3889BC2F95BA415899F250C1030EFE96","id":"EFECD2B37BF04D34BFE7F49EC9326C20","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":[" ![Image Name](https://cdn.kesci.com/upload/image/rhdcyu860w.gif?imageView2/0/w/960/h/960)  \n","\n","Source: https://www.science.org/toc/science/309/5731"]},{"cell_type":"markdown","metadata":{"_id":"08A6C46A8C7548B88E19549787864794","id":"4D7D7AB3CA8C49278F0BAD2362452559","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### **Q1:  What is the Uiverse Made of (physics)**  \n","\n","### **Q2:  What is the Biological Basis of Consciouness (psychological/cognitive science)**"]},{"cell_type":"markdown","metadata":{"_id":"3CDD8C902CF844838F6EC133AF5F0278","id":"8F0ADB2855A042F6A2732D42486E55F9","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### Q:   重要性和复杂度相似的问题，是否意味着研究方法也应该类似地复杂？"]},{"cell_type":"markdown","metadata":{"_id":"7B498D6777A040F58D136A7370C19CD5","id":"092934A684AE40EAABC8F7374CD4DEB2","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 物理学中的方法 (Methods in Physics):  \n","\n","#### Example 1: Webb telescope (韦伯望远镜)  (**equipment**)  \n","![Image Name](https://cdn.kesci.com/upload/image/rhdd0r46k3.png?imageView2/0/w/720/h/640)  "]},{"cell_type":"markdown","metadata":{"_id":"94DCF45875D74F5C8C594291479F0C02","id":"A1BB1E8F3A0D4282A195F3276AF1AE8B","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### Example 2: Big-team science (CERN, the European Organization for Nuclear Research) ---- **equipment & practices**  \n","\n","### Example 3: **Mathematics**"]},{"cell_type":"markdown","metadata":{"_id":"AD3FC69002994E39BE28CBF60204D3DA","id":"5019542BCD6F46788E674839385A2D75","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 其他研究人类智能的领域所采用的方法 (Methods in other fields that also study \"intelligence\")  \n","\n","## **AI**  \n","\n","![Image Name](https://cdn.kesci.com/upload/image/rhdd1sr5y2.png?imageView2/0/w/640/h/640)  \n"]},{"cell_type":"markdown","metadata":{"_id":"EF839BDD2BF6494992515AD0B586C1E1","id":"DA03169F08C446AEA8556C313097098A","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 心理科学的研究方法 [What do psychological scientists have?]  \n","##### 你们能够想到的研究方法包括哪些？  \n","\n","![Image Name](https://cdn.kesci.com/upload/image/rhdd2dgwc8.png?imageView2/0/w/640/h/640)  "]},{"cell_type":"markdown","metadata":{"_id":"17492B425D7F4C368972A8D13B18E05F","id":"475DD8AF1F5E4D119B5C9DFFD407359E","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### **实证研究：**  \n","* 质性研究  \n","* 观察法  \n","* 问卷  \n","* 行为实验  \n","* 眼动、生理数据记录  \n","* EEG/ERP/MEG  \n","* fMRI/PET/fNIRs  \n","* TMS/tDCS  \n","* ..."]},{"cell_type":"markdown","metadata":{"_id":"F1D4D510F66B43F6AAF9286F7CF2CB47","id":"0494884EA76046809C5FE83D1E68C82E","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### **统计方法：**  \n","* *t*-test  \n","* ANOVA  \n","* Correlation  \n","* Structural equation model (SEM)  \n","* ?"]},{"cell_type":"markdown","metadata":{"_id":"31255CB36D084CFF9EFC4701C3ECED72","id":"6BC0D95814974D9388782DD9122D3AA9","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 相关方法课程：  \n","* 心理测量  \n","* 心理统计（包括SPSS等）  \n","* 实验心理学（包括E-prime等）  \n","* ？"]},{"cell_type":"markdown","metadata":{"_id":"7067E7986432484F9AFA2101EA833087","id":"1492CF318296408F8C64EB848AA857F1","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["* 更好的仪器  \n","* **更好的统计/数据分析**  \n","* 更好的实践 (e.g., big-team science)"]},{"cell_type":"markdown","metadata":{"_id":"C58D40D1E3E3494C95A50EA4BB279690","id":"EAF014F53D0A4A858AE8D38F1AC1981A","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 原因2: 更复杂的数据  \n","\n","* 数据字化的时代，大数据  \n","* 神经成像/生理数据  \n","* 多模态的数据融合  \n","* ..."]},{"cell_type":"markdown","metadata":{"_id":"5B2851F7BD3C48B6BF31EB8608B94DE4","id":"37D70801AAB5459A806BE33418648AF8","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["  ##  <center>1.2 确实有更好的统计方法<center>"]},{"cell_type":"markdown","metadata":{"_id":"071AD928F7344E8EA4829E0C380ABEB0","id":"77ACAB0E470445A099E2D6AD9D35F595","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### <cenrer>贝叶斯统计 (Bayesian statistics) <cenrer>  \n","\n","\n","![Image Name](https://cdn.kesci.com/upload/image/rhdf3bb12c.png?imageView2/0/w/640/h/640)  \n","\n"]},{"cell_type":"markdown","metadata":{"_id":"76F47084C9A641C99AE0709B39834074","id":"82CA1F5560E343EE891901FC4B45A2D2","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["* 灵活/强大/能用  \n","* 易用  \n","* 可拓展性强  \n","* 方便跨学科交流  \n","* ..."]},{"cell_type":"markdown","metadata":{"_id":"6CB5494558464124A9736D5584F9AC94","id":"8226BD02E71F438BB3FA346DB9DABE45","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 通用/灵活/强大  \n","\n","* 通用：贝叶斯推断在多个学科特别是AI领域得到了广泛应用。  \n","* 灵活：结合先验知识与新数据，灵活调整模型以适应不同数据情境。  \n","* 强大：与频率主义学派相比，贝叶斯方法适用范围更广。"]},{"cell_type":"markdown","metadata":{"_id":"42FD9397038B4FB3900918244BC7B0D0","id":"D1718CCAEBCA4395AFD7FC76DF1C2897","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### （相对）易用  \n","\n","概率编程语言(Probabilistic Programming Languages, PPLs)的发展和普及  \n","\n","\n","PPLs: *computational languages for statistical modeling*  \n","\n","* Python\t \n","  * PyMC  \n","  * NumPyro   \n","* R  \n","  * Stan  \n","  * JAGS  \n","* BUGS  \n","* Julia  \n","  * Mamba  \n","  * Turing.jl  \n","* ..."]},{"cell_type":"markdown","metadata":{"_id":"0AD66181D27C489D8DBC6E0A509E3398","id":"8D6C42B26A4B4FB0A006CA840FF687B7","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["##### 大部分情况下，开发者使用它可以轻松地定义概率模型，然后程序会自动地求解模型。  \n","\n","\n","![Image Name](https://cdn.kesci.com/upload/image/rhdf4r9fbh.png?imageView2/0/w/640/h/640)  \n","\n","\n","Source: https://towardsdatascience.com/intro-to-probabilistic-programming-b47c4e926ec5  \n"]},{"cell_type":"markdown","metadata":{"_id":"B5B2EB51040141928D23D3EFB2E78D4C","id":"85633D3A963048D09BA7D1490AEA7AFB","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 可拓展  \n","\n","贝叶斯概念已经应用到以深度学习为中心的新技术的发展，包括深度学习框架(TensorFlow, Pytorch)，创建能力更强、数据驱动的模型。"]},{"cell_type":"markdown","metadata":{"_id":"127771B671484EFF9980C21DDBE91173","id":"6BC74FDC598B467C859A5AFC82134BC5","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 方便交流  \n","大部分PPLs都有类似的数据结构，但是不同的学科使用的语言不同。  \n","\n","心理学/社会科学/神经科学：  \n","* **PyMC**  (bambi)  \n","* Stan (brms)  \n","* BUGS"]},{"cell_type":"markdown","metadata":{"_id":"2D136AD0ECC846808F3C6B3A0E5AD96A","id":"5A4193B6F286479598A53681FB4B491E","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["<center><span style=\"font-size: 72px;\">Part 2: Three examples </span></center>"]},{"cell_type":"markdown","metadata":{"_id":"AC67C3A6ACF04E848A115D88F496F4C3","id":"D4DFC477EFAC411484A55CDFB273239A","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 例1：社会关系地位与幸福感的关系  \n","\n","实例的数据来自Many Labs 2 项目([文章](https://journals.sagepub.com/doi/10.1177/2515245918810225)、[数据](https://osf.io/8cd4r/))中的一个研究。  \n","\n","该研究探究了社会关系地位对于幸福感的影响 “Sociometric status and well-being”， (Anderson, Kraus, Galinsky, & Keltner, 2012)。  \n","\n","该数据集包括6905个被试的数据。  \n","\n","<p style=\"font-size:14px\">参考文献：</p>  \n","<p style=\"font-size:14px\">  \n","Anderson, C., Kraus, M. W., Galinsky, A. D., & Keltner, D. (2012). The local-ladder effect: Social status and subjective well-being. Psychological Science, 23(7), 764-771. https://doi.org/10.1177/0956797611434537  \n","</p>"]},{"cell_type":"code","execution_count":1,"metadata":{"_id":"719BD486C08D4E5595EF6D0528202C15","collapsed":false,"id":"28F94A52AC7542A78AF2B22687357D5D","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["import arviz as az\n","from scipy.stats import levene\n","from pingouin import ttest, tost, bayesfactor_ttest\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import pandas as pd\n","import pymc as pm\n","import xarray as xr\n","import pytensor.tensor as pt\n","import scipy.stats as stats\n","import seaborn as sns\n","from pytensor.tensor import TensorVariable\n","from scipy.stats import pearsonr\n","import graphviz\n","from graphviz import Digraph\n","\n","# 设置随机种子\n","rng = np.random.default_rng(202409)\n","\n","# 设置APA 7的画图样式\n","plt.rcParams.update({\n","    'figure.figsize': (4, 3),      # 设置画布大小\n","    'font.size': 12,               # 设置字体大小\n","    'axes.titlesize': 12,          # 标题字体大小\n","    'axes.labelsize': 12,          # 轴标签字体大小\n","    'xtick.labelsize': 12,         # x轴刻度字体大小\n","    'ytick.labelsize': 12,         # y轴刻度字体大小\n","    'lines.linewidth': 1,          # 线宽\n","    'axes.linewidth': 1,           # 轴线宽度\n","    'axes.edgecolor': 'black',     # 设置轴线颜色为黑色\n","    'axes.facecolor': 'white',     # 轴背景颜色（白色）\n","    'xtick.direction': 'in',       # x轴刻度线向内\n","    'ytick.direction': 'out',      # y轴刻度线向内和向外\n","    'xtick.major.size': 6,         # x轴主刻度线长度\n","    'ytick.major.size': 6,         # y轴主刻度线长度\n","    'xtick.minor.size': 4,         # x轴次刻度线长度（如果启用次刻度线）\n","    'ytick.minor.size': 4,         # y轴次刻度线长度（如果启用次刻度线）\n","    'xtick.major.width': 1,        # x轴主刻度线宽度\n","    'ytick.major.width': 1,        # y轴主刻度线宽度\n","    'xtick.minor.width': 0.5,      # x轴次刻度线宽度（如果启用次刻度线）\n","    'ytick.minor.width': 0.5,      # y轴次刻度线宽度（如果启用次刻度线）\n","    'ytick.labelleft': True,       # y轴标签左侧显示\n","    'ytick.labelright': False      # 禁用y轴标签右侧显示\n","})"]},{"cell_type":"code","execution_count":2,"metadata":{"_id":"16AAF0FC2C0C4C5FBD7B873F9FC348CD","collapsed":false,"id":"586ED9694477446ABBBE7BB18E6410FD","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 导入数据, 注意在和鲸和在自己电脑（本地）时有差异）\n","try:\n","  SMS_data = pd.read_csv('/home/mw/input/bayes3797/SMS_Well_being.csv')\n","except:\n","  SMS_data = pd.read_csv('data/SMS_Well_being.csv')\n","# 选择需要的列\n","SMS_data = SMS_data[['uID','variable','factor','Country']]\n","# 查看数据\n","SMS_data.head(2)"]},{"cell_type":"code","execution_count":3,"metadata":{"_id":"BE9D96AF08EE4CFCB7C8163D605646C5","collapsed":false,"id":"33F5E7A836384CA68C8852590F66CD34","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 把数据分为高低两种社会关系的地位的子数据以便画图与后续分析\n","factor_high = [sorted(SMS_data.query('factor==\"High\"').variable.loc[0:3000])]\n","factor_low = [sorted(SMS_data.query('factor==\"Low\"').variable.loc[0:3000])]"]},{"cell_type":"markdown","metadata":{"_id":"96EB26574D5B40518AC6E1436DE6130D","id":"AD648BF7D48A41978CD22AD3968BACEC","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 通过画图可视化两种社会关系地位对幸福感的影响  \n","\n","图中横坐标代表高低两种社会关系地位，纵坐标代表了主观幸福感评分。"]},{"cell_type":"code","execution_count":4,"metadata":{"_id":"8E23D40A124846029E77D81BEDD1CF58","collapsed":false,"id":"CBD09F3C6561416997A57205C6EBA877","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 定义绘图函数\n","def adjacent_values(vals, q1, q3):\n","    upper_adjacent_value = q3 + (q3 - q1) * 1.5\n","    upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])\n","\n","    lower_adjacent_value = q1 - (q3 - q1) * 1.5\n","    lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)\n","    return lower_adjacent_value, upper_adjacent_value\n","\n","def set_axis_style(ax, labels):\n","    ax.xaxis.set_tick_params(direction='out')\n","    ax.xaxis.set_ticks_position('bottom')\n","    ax.set_xticks(np.arange(1, len(labels) + 1), labels=labels)\n","    ax.set_xlim(0.25, len(labels) + 0.75)\n","    ax.set_xlabel('Soceity Status')\n","\n","def plot_violin_apa7(data, x_labels, y_label, title=None):\n","    \n","    fig, ax = plt.subplots(figsize=(6, 4))  # 调整图形大小\n","\n","    # 创建小提琴图\n","    parts = ax.violinplot(data, showmeans=False, showmedians=False, showextrema=False)\n","\n","    # 设置小提琴图的样式\n","    for pc in parts['bodies']:\n","        pc.set_facecolor('#D43F3A')\n","        pc.set_edgecolor('black')\n","        pc.set_alpha(0.8)\n","\n","    # 计算分位数和须\n","    quartile1, medians, quartile3 = np.percentile(data, [25, 50, 75], axis=1)\n","    whiskers = np.array([adjacent_values(sorted_array, q1, q3)\n","                         for sorted_array, q1, q3 in zip(data, quartile1, quartile3)])\n","\n","    whiskers_min, whiskers_max = whiskers[:, 0], whiskers[:, 1]\n","\n","    # 绘制中位数和须\n","    inds = np.arange(1, len(medians) + 1)\n","    ax.scatter(inds, medians, marker='o', color='white', s=30, zorder=3)\n","    ax.vlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5)\n","    ax.vlines(inds, whiskers_min, whiskers_max, color='k', linestyle='-', lw=1)\n","\n","    # 设置x轴和y轴标签\n","    ax.set_xticks(np.arange(1, len(x_labels) + 1))\n","    ax.set_xticklabels(x_labels)\n","    ax.set_ylabel(y_label)\n","\n","    # 设置y轴从0开始\n","    ax.set_ylim(0, None)\n","\n","    # 保留左侧和底部的框线，移除右侧和顶部的框线\n","    ax.spines['bottom'].set_visible(True)\n","    ax.spines['left'].set_visible(True)\n","    ax.spines['bottom'].set_linewidth(1)\n","    ax.spines['left'].set_linewidth(1)\n","\n","    ax.spines['top'].set_visible(False)\n","    ax.spines['right'].set_visible(False)\n","\n","    # 如果有标题，则设置标题\n","    if title:\n","        ax.set_title(title, pad=10)\n","\n","    # 设置x轴风格\n","    set_axis_style(ax, x_labels)\n","\n","    # 图形的显示\n","    plt.tight_layout()\n","    plt.show()"]},{"cell_type":"code","execution_count":5,"metadata":{"_id":"A105B16EA7BE491B96B8B2A2AF884612","collapsed":false,"id":"B454131BD27F47A0BD819FFF52AFADF5","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 示例数据和函数调用\n","plot_data = [np.random.normal(70, 10, 100), np.random.normal(60, 15, 100)]\n","plot_violin_apa7(plot_data, ['Low', 'High'], 'Well-being',\n","                 'The impact of social status on well-being')\n"]},{"cell_type":"markdown","metadata":{"_id":"491C6E58B2C74EC5BC05EBCF8352B0BB","id":"0943D98E598844B89660548E285EF447","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 通过*t*检验，分析两种社会关系地位下幸福感的差异  "]},{"cell_type":"code","execution_count":6,"metadata":{"_id":"414AFC72EA304D8B84AB76B1D0D7AF43","collapsed":false,"id":"536C0D26FCA9461EA294492EE5BC3D6D","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# levene检验\n","levene_stat, levene_p = levene(SMS_data['variable'][SMS_data['factor'] == 'High'], \n","                               SMS_data['variable'][SMS_data['factor'] == 'Low'])\n","print(f'Levene Test p-value: {levene_p}')"]},{"cell_type":"markdown","metadata":{"_id":"B6719A2E9C0E48C49CE0F2A1D1B17CE4","id":"41FA5067AAA54B78B477386663F2503C","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["根据独立样本*t*检验结果，低社会地位组（*M* = 0.014, *SD* = 0.66）和高社会地位组（*M* = -0.014, *SD* = 0.67）之间的差异在统计学上不显著，*t* = 1.76, *p* = 0.079。  \n","\n","这意味着我们无法在传统显著性水平（α = 0.05）下拒绝原假设($H_0$)。因此高社会地位和低社会地位下的幸福感差异在统计学上不是显著的。"]},{"cell_type":"code","execution_count":7,"metadata":{"_id":"92379E86F63943B296536AC852716200","collapsed":false,"id":"5AC9FAE9538245AAA6C387CB7A2BD782","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["SMS_low = SMS_data.query('factor==\"Low\"').variable.values\n","SMS_high = SMS_data.query('factor==\"High\"').variable.values\n","print(\n","    f\"Low Social Status：{np.around(np.mean(SMS_low),3)} ± {np.around(np.std(SMS_low),2)}；\",\n","    f\"High Social Status：{np.around(np.mean(SMS_high),3)} ± {np.around(np.std(SMS_high),2)}\")\n","\n","# 进行独立样本t检验  \n","results = stats.ttest_ind(\n","    a= SMS_low,\n","    b= SMS_high, \n","    equal_var=True)\n","print(f\"t={round(results[0],2)}, p={round(results[1],3)}\")"]},{"cell_type":"markdown","metadata":{"_id":"17220AF17B654224A3BE1BE01A972FC3","id":"74FA08B8F53E4ACEA95A779AA221BEF5","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["[Two one-sided tests (TOST)检验](https://aaroncaldwell.us/TOSTERpkg/)是一种常用于等效性检验(equivalence tests)的方法，其目的是评估两个组之间的差异是否可以被视为“相等”。在该方法中，等效性被定义为组间差异位于预先设定的“等效边界”范围内。如果组间的差异落在这一范围内，则可以认为这两个组在统计上是等效的。  \n","\n","在本例中，我们可以将等效边界设定为0.2（bound=0.2），意味着如果两个组之间的差异不超过0.2，就可以认为它们是等效的。  \n","\n","因此，检验得出的*p*值（2.265256e-27）可以表明有非常强的证据表明这两个组之间的差异在等效边界之内。"]},{"cell_type":"code","execution_count":8,"metadata":{"_id":"DC16CB5BFB484283A4273CD500401BC7","collapsed":false,"id":"49DF1C90E64B4EB1B259FE0E9D2561C4","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 双单侧检验（Two one-side test, TOST）\n","tost_res = tost(x=SMS_data['variable'][SMS_data['factor'] == 'High'], \n","                y=SMS_data['variable'][SMS_data['factor'] == 'Low'], \n","                bound=0.20, paired=False) # 将等效边界值设为0.2\n","print(tost_res)"]},{"cell_type":"markdown","metadata":{"_id":"C9BF44542134436E96851ABA96606F4B","id":"23E7B32764C6406886CD43ABEFFCA945","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 通过贝叶斯因子替代*t*检验  \n","传统的零假设显著性检验（Null hypothesis significance test, NHST）的框架之下，*t*检验只提供了一个二分的结果：拒绝或者无法拒绝$H_0$。 但 ***p* = 0.079**这样的结果无法支持$H_0$。而贝叶斯因子（Bayes Factor, BF）方法可以提供一种更直观和渐进的方式来评估数据支持原假设（无效假设，$H_0$）还是备择假设($H_1$)。 "]},{"cell_type":"code","execution_count":9,"metadata":{"_id":"CB1887F8E9014ACFB931B45C3A53806D","collapsed":false,"id":"D241094974334C5B91E7E1EB4BD68F6D","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 贝叶斯因子\n","## 比较高低社会关系地位的社会关系的效应\n","ttest_res = ttest(SMS_data['variable'][SMS_data['factor'] == 'High'], \n","                     SMS_data['variable'][SMS_data['factor'] == 'Low'], \n","                     paired=False)\n","\n","## 计算贝叶斯因子\n","t_value = ttest_res['T'].values[0] # 提取t值\n","dof = ttest_res['dof'].values[0] # 提取自由度\n","\n","# 计算‘High’组和‘Low’组的样本量大小\n","sample_size_high = len(SMS_data['variable'][SMS_data['factor'] == 'High'])\n","sample_size_low = len(SMS_data['variable'][SMS_data['factor'] == 'Low'])\n","\n","# 使用默认的r值= 0.707\n","BF_sms = bayesfactor_ttest(t_value, nx=sample_size_high, ny=sample_size_low, paired=False, r=0.707)\n","\n","# 输出贝叶斯因子\n","print(BF_sms)"]},{"cell_type":"markdown","metadata":{"_id":"FC9EF6B040C343C9A2B433782ECFACB3","id":"3B6E8A2B99E34829BC7E7F2F91EC25B2","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["贝叶斯因子为$BF_{10}$ = 0.127，或者$BF_{01}$ = 1/0.127 = 7.87，这表明对于当前数据支持零假设$H_0$ ，说明高低社会关系地位组之间的社会关系效应没有显著差异。  \n","\n","贝叶斯因子（Bayes Factor，$BF$）  \n","\n","| 贝叶斯因子，$BF_{01}$ | 解释标准                      |  \n","|-----------------------------|-------------------------------|  \n","| > 100                        | 极强的证据支持$H_0$    |  \n","| 30 ~ 100                     | 非常强的证据支持$H_0$ |  \n","| 10 ~ 30                      | 较强的证据支持$H_0$    |  \n","| 3 ~ 10                       | 中等程度的证据支持$H_0$ |  \n","| 1 ~ 3                        | 较弱的证据支持$H_0$    |  \n","| 1                            | 没有证据                      |  \n","| 1/3 ~ 1                      | 较弱的证据支持$H_1$    |  \n","| 1/10 ~ 1/3                   | 中等程度的证据支持$H_1$|  \n","| 1/30 ~ 1/10                  | 较强的证据支持$H_1$    |  \n","| 1/100 ~ 1/30                 | 非常强的证据支持$H_1$  |  \n","| < 1/100                      | 极强的证据支持$H_1$    |  \n","\n","<p style=\"font-size:14px\">参考文献：</p>  \n","\n","<p style=\"font-size:14px\">  \n","胡传鹏, 孔祥祯, Wagenmakers, E.-J., Ly, A., 彭凯平 (2018). 贝叶斯因子及其在JASP中的实现. 心理科学进展, 26(6), 951-965.  \n","</p>  \n","\n","<p style=\"font-size:14px\">  \n","Wagenmakers, E.-J., & Brown, S. (2007). On the linear relation between the mean and the standard deviation of a response time distribution. Psychological Review, 114(3), 830-841. https://doi.org/10.1037/0033-295X.114.3.830  \n","</p>"]},{"cell_type":"code","execution_count":10,"metadata":{"_id":"A0C5D5116649486481073CC5AD8C457F","collapsed":false,"id":"CDF4ABBC0B9A411F8C0397B465C7561A","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 敏感性分析\n","# Cauchy (0, 1)\n","BF_sms_1 = bayesfactor_ttest(t_value, nx=sample_size_high, ny=sample_size_low, paired=False, r=1)\n","print(BF_sms_1)"]},{"cell_type":"markdown","metadata":{"_id":"A83A7E640EDF43F9A9A7180DEF5D6BB6","id":"91CF542038224251A9FBC3EC032CFFF6","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 贝叶斯推断  \n","\n","\n","这个模型是怎么来的呢？  \n","\n","一个简单的线性模型：  \n","\n","1. 通过建立线性模型去替代原本的*t*检验模型。  \n","\n","2. 通过PyMC对后验进行采样  \n","\n","3. 通过Arviz对结果进行展示，辅助统计推断"]},{"cell_type":"code","execution_count":11,"metadata":{"_id":"9B93C356B97C4DFBA43E22CC0CD4D7C3","collapsed":false,"id":"BC6DF62574DC45E4AA4F2985AACBA8B1","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 通过pymc建立基于贝叶斯的线性模型\n","x = pd.factorize(SMS_data.factor)[0] # high为0，low为1\n","# 设置beta1的先验分布的尺度参数，与r=0.707相匹配\n","beta1_scale = 0.707\n","\n","# 建立模型\n","with pm.Model() as linear_regression:\n","    sigma = pm.HalfCauchy(\"sigma\", beta=2)\n","    beta0 = pm.Normal(\"beta0\", 0, sigma=5)\n","    beta1 = pm.Normal(\"beta1\", 0, sigma=beta1_scale)\n","    # beta1 = pm.StudentT(\"beta1\", nu=1, mu=0, sigma=beta1_scale)  # 使用 StudentT 分布接近 Cauchy 分布\n","    # beta1 = pm.Cauchy(\"beta1\", alpha=0, beta=beta1_scale)  # 使用 Cauchy 分布，参数 beta 与 r 值对应\n","    x = pm.Data(\"x\", x)\n","    mu = pm.Deterministic(\"μ\", beta0 + beta1 * x)\n","    pm.Normal(\"y\", mu=mu, sigma=sigma, observed=SMS_data.variable)"]},{"cell_type":"markdown","metadata":{"_id":"5C5606ADD0D14E4FA0E49D52D9475C95","id":"6D4125225E9D44AC86DFD31FEB6C8736","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["可以通过PyMC自带的可视化工具将模型关系可视化。  \n","\n","x 为自变量，其中1为低社会关系，0为高社会关系。  \n","\n","参数 $\\beta_0$ 是线性模型的截距，而 $\\beta_1$ 是斜率。  \n","\n","截距代表了高社会关系地位被试的幸福感；而截距加上斜率表示低社会关系地位被试的幸福感。  \n","\n","参数$\\sigma$是残差，因变量$y$即主观幸福感。  \n","\n","模型图展示了各参数通过怎样的关系影响到因变量。"]},{"cell_type":"code","execution_count":12,"metadata":{"_id":"A518B086592A43B39C72054F3A21A2F8","collapsed":false,"id":"60210A051FE04F358FC268FEECC2BF49","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["pm.model_to_graphviz(linear_regression)"]},{"cell_type":"markdown","metadata":{"_id":"FC18730524054280A26987504048E47F","id":"AE2780344F24486A95F3A4C2B17F321A","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["PyMC 贝叶斯模型结合 Arviz 计算得到的贝叶斯因子结果(基于 Savage-Dickey 方法)与贝叶斯*t*-test结果接近。"]},{"cell_type":"code","execution_count":13,"metadata":{"_id":"0D8B31FCE62D4C4990E458097A1AC127","collapsed":false,"id":"83CA1B3AF09347FEB84BC69298FC42D5","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 模型拟合过程 (mcmc采样过程)\n","with linear_regression:\n","    # 先验采样\n","    prior_checks = pm.sample_prior_predictive(samples=5000)\n","    # 后验采样\n","    idata = pm.sample(2000, tune=1000, target_accept=0.9, return_inferencedata=True)\n","    # 将先验采样的结果合并到推断数据中\n","    idata.extend(pm.sample_prior_predictive(samples=500, model=linear_regression))"]},{"cell_type":"code","execution_count":14,"metadata":{"_id":"4EEC141C4FDC40419B5F46E1685E1051","collapsed":false,"id":"4C275D99AEC648C3AF3D9B3989DB7CAA","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["fig, axs = plt.subplots(1, 2, figsize=(6, 3))\n","az.plot_posterior(prior_checks.prior[\"beta1\"], ax=axs[0])\n","axs[0].set_title(\"Prior\")\n","az.plot_posterior(idata.posterior[\"beta1\"], ax=axs[1], color=\"C1\")\n","axs[1].set_title(\"Posterior\")\n","plt.show()"]},{"cell_type":"code","execution_count":15,"metadata":{"_id":"E6CC757F84054281852CBA381F18FB80","collapsed":false,"id":"A48FF5F13CE943B2A19ADDF4702F1013","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["print(f\"The Bayes T-test is {BF_sms}\")\n","ax = az.plot_bf(idata, var_name=\"beta1\", ref_val=0)\n","ax[1].set_xlim(-0.5, 0.5)\n","ax[1].set_xlabel(\"beta1 \\n(represents the difference \\nbetween two groups)\")\n","plt.show()"]},{"cell_type":"markdown","metadata":{"_id":"4260118E213944E5BF1EB9B2950E59F8","id":"A36D3DA0EA3743968C9D3985F892358B","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 例2 贝叶斯分层模型（Hierarchical/Multi-level Model） 可以更准确地估计信度  \n","\n","在前面的内容中，我们通过社会关系地位（高与低）对幸福感的影响进行了可视化，并使用贝叶斯因子和贝叶斯推断对模型进行了进一步的分析。  \n","\n","现实世界的数据往往存在分层结构（例如，数据可能来自不同的群体、地区、时间段等），如何更好地处理数据内在的层次结构，更加准确地估计出感兴趣的效应（如社会关系地位对幸福感的影响），正是分层模型所能解决的。  "]},{"cell_type":"markdown","metadata":{"_id":"00D798806A704698A63F49F8F759BE8B","id":"2DEA384712194B95AB50001D214007D7","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 分层模型（Hierarchical Model）的特殊运用：  信度估计  \n","\n","例2的数据来源于Haines (2020)的论文（ https://osf.io/preprints/psyarxiv/xr7y3 ）。  \n","\n","本文的研究问题是：认知任务作为测量个体差异的工具，是否真的信度很差？  \n","\n","<p style=\"font-size:14px\">参考文献：</p>  \n","<p style=\"font-size:14px\">  \n","Haines, N., Kvam, P. D., Irving, L. H., Smith, C., Beauchaine, T. P., Pitt, M., & Turner, B. (2020, August 24). Theoretically informed generative models can advance the psychological and brain sciences: Lessons from the reliability paradox. PsyArXiv. https://doi.org/10.31234/osf.io/xr7y3  \n","</p>"]},{"cell_type":"markdown","metadata":{"_id":"4F37C9B333A144BEA69A63EE86CC288D","id":"8C2DB795085E43FA91D23CEE8FE99EA7","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["例2数据集包括Flanker任务中的反应时间（RT）和正确率数据。Flanker任务要求被试对中央箭头的方向作出反应，同时忽略周围的干扰箭头。  \n","\n","\t•\t反应时间 (RT)：以秒为单位，记录每次试验的反应时间。  \n","\t•\t正确率 (Correct)：记录被试反应是否正确。  \n","\t•\t条件 (Condition)：任务分为一致性和不一致性试验，箭头方向是否一致会影响被试的反应时间。  \n","\t•\t试验和区块：任务分为多个区块，每个区块包含一系列试验。  \n","\n","<div style=\"text-align: center;\">  \n","    <img src=\"https://tse1-mm.cn.bing.net/th/id/OIP-C.mWWpZdVKA6TlyCuwQlnQSQHaEs?rs=1&pid=ImgDetMain\" alt=\"Flanker Example\" width=\"640\" height=\"640\">  \n","    <p style=\"font-size:12px\">(Kim et al., 2022)</p>  \n","</div>"]},{"cell_type":"code","execution_count":16,"metadata":{"_id":"FA24B3321FA54A6EABEE57D80A5A32F4","collapsed":false,"id":"35ECA4769DCE49CCA36E3E51459CD2DE","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 导入例2数据\n","try:\n","  df_flanker = pd.read_csv('/home/mw/input/bayes3797/flanker_1.csv')\n","except:\n","  df_flanker = pd.read_csv('data/flanker_1.csv')\n","\n","# 分层模型数据预处理\n","df_model = df_flanker.copy()\n","df_model = df_model[(df_model.RT > 0) & (df_model.Condition != 1)].reset_index(drop=True)\n","# 将条件进行重新编码，1为不一致，0为一致\n","df_model[\"Condition\"] = np.where(df_model[\"Condition\"] == 2, 1,df_model[\"Condition\"])\n","# 将时间变量进行重新编码\n","df_model[\"Time\"].replace(1, 0, inplace=True)\n","df_model[\"Time\"].replace(2, 1, inplace=True)\n","# 生成所有试次的索引\n","df_model[\"trial_idx\"] = range(len(df_model))\n","# 重新编码被试编号\n","df_model['subj_num'] = df_model['subj_num'] - 1\n","# 每个被试不同时间rt的最小值\n","rt_min = df_model.groupby(['subj_num','Time']).RT.min().unstack().to_numpy()"]},{"cell_type":"code","execution_count":17,"metadata":{"_id":"CDABAD208A5E4DC98EC8C1B4D94007D4","collapsed":false,"id":"25C03CA6897D45D19B56952AAC124943","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["df_model.head()"]},{"cell_type":"markdown","metadata":{"_id":"A56BFF5F325F44A1899FCBB2EC43CD19","id":"5671F9E1E78E4254A9D8D1940C401268","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["##  <center>传统方法：初测-重测的相关系数(Two-stage model) <center>"]},{"cell_type":"code","execution_count":18,"metadata":{"_id":"CEBF22C74DC0416D94B6A440F4CEE29C","collapsed":false,"id":"75C6AB0DAD2044BE9D5A26F20F42E4A6","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# two-stage model 数据预处理\n","\n","df_trad = df_flanker.copy()\n","# 选择反应时大于0且条件不为1\n","df_trad = df_trad[(df_trad.RT > 0) & (df_trad.Condition != 1)].reset_index(drop=True)\n","# 将条件进行重新编码，2为不一致，0为一致\n","df_trad[\"Condition\"] = df_trad[\"Condition\"].replace({2: 'incon', 0: 'con'})\n","# 将时间变量进行重新编码\n","df_trad[\"Time\"] = df_trad[\"Time\"].replace({1: 't1', 2: 't2'})\n","# 根据条件分组\n","df_trad = df_trad.groupby(['subj_num','Condition','Time'])['RT'].agg(['mean','std']).reset_index()\n","# 将需要做相关的转成长数据\n","df_trad= df_trad.pivot(index='subj_num',columns=['Condition','Time'],values=['mean','std']).reset_index()\n","df_trad.columns = [\n","    'subj_num' if col1 == 'subj_num' else f'{col1}_{col2}_{col3}' \n","    for col1, col2, col3 in df_trad.columns]\n","# 关注平均值、标准差的差值\n","df_trad['mean_contrast_t1'] = df_trad['mean_con_t1'] - df_trad['mean_incon_t1']\n","df_trad['mean_contrast_t2'] = df_trad['mean_con_t2'] - df_trad['mean_incon_t2']\n","df_trad['sd_contrast_t1'] = df_trad['std_con_t1'] - df_trad['std_incon_t1']\n","df_trad['sd_contrast_t2'] = df_trad['std_con_t2'] - df_trad['std_incon_t2']\n","df_trad = df_trad[['subj_num','mean_contrast_t1','mean_contrast_t2','sd_contrast_t1','sd_contrast_t2']]"]},{"cell_type":"code","execution_count":19,"metadata":{"_id":"60ACFC9C97A543B6A29961D0BF55C53E","collapsed":false,"id":"46245583FC634764A479A5F587DFB961","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 经过数据预处理后，定义函数，计算time 1和time 2数据的皮尔逊相关系数\n","def pearson_df(method, var, col1, col2): # 定义函数，用于计算皮尔逊相关系数\n","    contrast_cor = pearsonr(col1, col2) # 计算皮尔逊相关系数\n","    contrast_coef = contrast_cor[0]\n","    ci_low, ci_high = contrast_cor.confidence_interval(confidence_level=0.95) # 计算置信区间\n","    \n","    # 创建结果数据框\n","    result_df = pd.DataFrame({\n","        'mean': [contrast_coef],\n","        'hdi_2.5%': [ci_low],\n","        'hdi_97.5%': [ci_high]},\n","        index = [['Two-Stage'],\n","                [f'{method}_{var}']])\n","\n","    return result_df"]},{"cell_type":"code","execution_count":20,"metadata":{"_id":"59B78A26653B4254AD221B958C36EEB9","collapsed":false,"id":"3C2675F9A6ED4892AD9C5F3DF71D600D","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["trad_mu = pearson_df(method = \"trad\",  \n","           var = \"mean\", # 均值\n","           col1 = df_trad['mean_contrast_t1'], \n","           col2 = df_trad['mean_contrast_t2']) # 两个时间点的均值对比\n","\n","trad_sigma = pearson_df(method = \"trad\", # 传统方法\n","           var = \"sd\", \n","           col1 = df_trad['sd_contrast_t1'], \n","           col2 = df_trad['sd_contrast_t2'])\n","# 合并结果\n","trad_result = pd.concat([trad_mu, trad_sigma]) \n","trad_result = trad_result.reset_index() # 重置索引\n","trad_result[\"level_1\"] = trad_result[\"level_1\"].replace({'trad_mean': 'mu', 'trad_sd': 'sigma'}) # 重命名列名\n","print(trad_result)"]},{"cell_type":"markdown","metadata":{"_id":"BC48F771E9FC4CD5909A46A514D56304","id":"B80D03A96CB8454E83C8E31C92C5634F","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### <center>贝叶斯分层模型（Hierarchical Model）<center>  \n","###  <center>分层的广义线性模型: Shifted Lognormal model <center>"]},{"cell_type":"code","execution_count":21,"metadata":{"_id":"3CCD335481474B4F8C111AFF0FA05040","collapsed":false,"id":"D42EFAFE8CEF4467BD4C8BAC6D708F92","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["def logshift_model(data):\n","    def shifted_lognormal(mu, sigma, loc, size=None):\n","        return loc + pm.LogNormal.dist(mu=mu, sigma=sigma, size=size)\n","\n","    coords = {\"cond\": data['Condition'].unique(),\n","            \"time\": data['Time'].unique(),\n","            \"subj\": data['subj_num'].unique(),\n","            \"trial\": data['trial_idx']}\n","\n","\n","    with pm.Model(coords=coords) as model:\n","\n","        rho_R_mu = pm.LKJCorr('rho_R_mu', n=2, eta=1)\n","        rho_R_sigma = pm.LKJCorr('rho_R_sigma', n=2, eta=1)\n","\n","        ######\n","        triu_idx = np.triu_indices(2, k=1)\n","        mu_corr_upper = pt.set_subtensor(pt.zeros((2, 2))[triu_idx], rho_R_mu)\n","        sigma_corr_upper = pt.set_subtensor(pt.zeros((2, 2))[triu_idx], rho_R_sigma)\n","        R_mu = pt.eye(2) + mu_corr_upper + mu_corr_upper.T\n","        R_sigma = pt.eye(2) + sigma_corr_upper + sigma_corr_upper.T\n","        L_R_mu = pt.linalg.cholesky(R_mu)\n","        L_R_sigma = pt.linalg.cholesky(R_sigma)\n","\n","        #####\n","\n","        # Group-level parameter means\n","        mu_mean_base = pm.Normal('mu_mean_base',mu=0, sigma=1, dims=\"time\")\n","        mu_sd_base = pm.HalfNormal('mu_sd_base', sigma=1, dims=\"time\")\n","\n","        \n","        sigma_mean_base = pm.Normal('sigma_mean_base', mu=0, sigma=1, dims=\"time\")\n","        sigma_sd_base = pm.HalfNormal('sigma_sd_base', sigma=1, dims=\"time\")\n","\n","        mu_mean_delta = pm.Normal('mu_mean_delta', mu=0, sigma=1, dims=\"time\")\n","        mu_sd_delta = pm.HalfNormal('mu_sd_delta', sigma=1, dims=\"time\") #/*\n","\n","        sigma_mean_delta = pm.Normal('sigma_mean_delta', mu=0, sigma=1, dims=\"time\")\n","        sigma_sd_delta = pm.HalfNormal('sigma_sd_delta', sigma=1, dims=\"time\") #/*\n","\n","        ndt_mean = pm.Normal('ndt_mean', mu=0, sigma=1, dims=\"time\")\n","        ndt_sigma = pm.Normal('ndt_sigma', mu=0, sigma=1, dims=\"time\")\n","\n","        # to make diagnol matrix/ can multiply with L_R_mu/L_R_sigma\n","        mu_sd_delta_re = pt.diag(mu_sd_delta)\n","        sigma_sd_delta_re = pt.diag(sigma_sd_delta)\n","        L_S_mu =  pm.Deterministic(\"L_S_mu\",pt.dot(mu_sd_delta_re,L_R_mu))\n","        L_S_sigma = pm.Deterministic(\"L_S_sigma\", pt.dot(sigma_sd_delta_re, L_R_sigma))\n","        \n","        # individual-level parameters/congruent\n","        mu_i_base_pr = pm.Normal('mu_i_base_pr', mu=0, sigma=1, dims=[\"subj\",\"time\"])\n","        sigma_i_base_pr = pm.Normal(\"sigma_i_base_pr\", mu=0, sigma=1, dims=[\"subj\",\"time\"])\n","        # individual-level parameters/incongruent\n","        mu_i_delta_pr = pm.Normal(\"mu_i_delta_pr\", mu=0, sigma=1, dims=[\"time\",\"subj\"])\n","        sigma_i_delta_pr = pm.Normal(\"sigma_i_delta_pr\", mu=0, sigma=1, dims=[\"time\",\"subj\"])\n","\n","        ndt_i_pr = pm.Normal('ndt_i_pr', mu=0, sigma=1, dims=[\"subj\",\"time\"])\n","        rv = pm.Normal.dist(0,1)\n","        phi = pm.logcdf(rv,ndt_mean+ndt_sigma*ndt_i_pr)\n","        phi = pm.math.exp(phi)\n","        ndt_i = pm.Deterministic('ndt_i', phi*rt_min, dims=[\"subj\",\"time\"])\n","\n","    \n","        # 得到公式2的后半部分\n","        mu_i_delta_tilde = pm.Deterministic(\"mu_i_delta_tilde\", pt.dot(L_S_mu, mu_i_delta_pr))\n","        sigma_i_delta_tilde = pm.Deterministic(\"sigma_i_delta_tilde\", pt.dot(L_S_sigma, sigma_i_delta_pr))\n","\n","        #----------------------------\n","        \n","        # mu congruent\n","        mu_i_base = pm.Deterministic(\"mu_i_base\", mu_mean_base + mu_sd_base*mu_i_base_pr,dims=[\"subj\",\"time\"])\n","        # sigma congruent\n","        sigma_i_base = pm.Deterministic(\"sigma_i_base\", sigma_mean_base + sigma_sd_base*sigma_i_base_pr,dims=[\"subj\",\"time\"])\n","        # congruent effect\n","        mu_i_effect = pm.Deterministic(\"mu_i_effect\", mu_mean_delta + mu_i_delta_tilde.T,dims=[\"subj\",\"time\"])\n","        # sigma incongruent\n","        sigma_i_effect = pm.Deterministic(\"sigma_i_effect\", sigma_mean_delta + sigma_i_delta_tilde.T,dims=[\"subj\",\"time\"])\n","        # mu incongruent\n","        mu_i_incon = pm.Deterministic(\"mu_i_incon\", mu_i_base + mu_i_effect,dims=[\"subj\",\"time\"])\n","        # sigma incongruent\n","        sigma_i_incon = pm.Deterministic(\"sigma_i_incon\", sigma_i_base + sigma_i_effect,dims=[\"subj\",\"time\"])\n","\n","        mu = pm.Deterministic(\"mu\",pm.math.stack([mu_i_base,mu_i_incon]), dims=[\"cond\",\"subj\",\"time\"])\n","        sigma_stack = pm.Deterministic(\"sigma_stack\",pm.math.stack([sigma_i_base,sigma_i_incon]),dims=[\"cond\",\"subj\",\"time\"])\n","        sigma = pm.Deterministic(\"sigma\", pm.math.exp(sigma_stack), dims=[\"cond\",\"subj\",\"time\"])\n","\n","        time_idx = pm.MutableData(\"time_idx\",data.Time, dims=\"trial\")\n","        subj_idx = pm.MutableData(\"subj_idx\",data.subj_num, dims=\"trial\")\n","        cond_idx = pm.MutableData(\"cond_idx\",data.Condition, dims=\"trial\")\n","\n","        likelihood = pm.CustomDist(\"likelihood\",\n","                    mu[cond_idx, subj_idx, time_idx], \n","                    sigma[cond_idx, subj_idx, time_idx],\n","                    ndt_i[subj_idx, time_idx],\n","                    dist = shifted_lognormal,\n","                    observed=data.RT,\n","                    dims=\"trial\")\n","                                    \n","        # pred = pm.Deterministic(\"pred\", likelihood + ndt_i[subj_idx, time_idx], dims=\"trial\")\n","\n","    return model"]},{"cell_type":"code","execution_count":22,"metadata":{"_id":"4147A1E9161E46C4B28E07DDED2E0C51","collapsed":false,"id":"F0407E18AF4D46DCB3D798A00BF1389F","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 根据不同的方法选择不同的模型\n","def process_model(data, distribution):\n","    if distribution == 'log_shift':\n","        return logshift_model(data)"]},{"cell_type":"code","execution_count":23,"metadata":{"_id":"A42ECA07516A4F879F10051B5A931A95","collapsed":false,"id":"9054D58549464C5F91554FC67211A184","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 进行先验预测检验并输出\n","def prior_predictive_check(model, samples=50, random_seed=43201):\n","    model_prior_check = pm.sample_prior_predictive(\n","        samples=samples,\n","        model=model,\n","        var_names=[\"mu\",\"sigma\"],\n","        random_seed=random_seed\n","    )\n","\n","    fig, ax = plt.subplots(1, 2, figsize = (15,5))\n","    fig.suptitle(\"Prior predictive check\")\n","    ax[0].set_title(\"mu\")\n","    az.plot_dist(model_prior_check.prior[\"mu\"], ax=ax[0])\n","\n","    ax[1].set_title(\"sigma\")\n","    az.plot_dist(model_prior_check.prior[\"sigma\"], ax=ax[1])\n","\n","    return fig"]},{"cell_type":"code","execution_count":24,"metadata":{"_id":"882FA1DBD78D4FA18A49C54938182528","collapsed":false,"id":"1F0092D662C64818A01DE0C1FBC169F6","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 进行采样\n","def model_sampling(model):\n","    trace = pm.sample(draws=2000,            # 使用mcmc方法进行采样，draws为采样次数\n","                    tune=1000,                    # tune为调整采样策略的次数，可以决定这些结果是否要被保留\n","                    chains=4,                     # 链数\n","                    cores=4,\n","                    discard_tuned_samples= True,  # tune的结果将在采样结束后被丢弃\n","                    random_seed=43201,\n","                    target_accept=0.8,\n","                    model=model)\n","    return trace"]},{"cell_type":"code","execution_count":25,"metadata":{"_id":"DABE830946A4436F889420FC1A668CEA","collapsed":false,"id":"3F639546A25F4B76B17CCF594AD6B914","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 对重测信度参数进行总结\n","def diagnostic_summary(trace, model_name):\n","    diagnostic = az.plot_trace(trace,\n","                               var_names = [\"rho_R_mu\", \"rho_R_sigma\"],\n","                               figsize=(15,10))\n","    hdi_sum = az.summary(trace, \n","                        var_names =[\"rho_R_mu\", \"rho_R_sigma\"],\n","                        hdi_prob = 0.95)\n","    hdi_sum = hdi_sum[[\"mean\",\"hdi_2.5%\",\"hdi_97.5%\"]]\n","\n","    hdi_sum.index = pd.MultiIndex.from_arrays([[f'{model_name}'] * len(hdi_sum.index), hdi_sum.index])\n","    return diagnostic, hdi_sum"]},{"cell_type":"code","execution_count":26,"metadata":{"_id":"EFF8CCEF89AB4997BD4078225A79F780","collapsed":false,"id":"6192336A08C5437A83F00368F126378C","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 集合需要的结果并输出\n","import gc\n","\n","def result_output(data, distribution, model_name):\n","    model = process_model(data=data, distribution=distribution)\n","    prior_plot = prior_predictive_check(model, samples=50, random_seed=43201)\n","    trace = model_sampling(model)\n","    diag, hdi = diagnostic_summary(trace, model_name)\n","    del trace\n","    gc.collect()\n","    return diag, hdi, prior_plot"]},{"cell_type":"code","execution_count":27,"metadata":{"_id":"A6F0BF8EB8CF43AEA448A74AED1D043B","collapsed":false,"id":"998B286399BB407E934366A19C1FC902","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 使用4核16G的计算资源，运行以下代码，需要约2小时\n","diag_logshift, hdi_logshift, priorplot_logshift = result_output(df_model, \"log_shift\",\"Shifted Lognormal\")"]},{"cell_type":"markdown","metadata":{"_id":"7B2340339095410C9A514062238E171C","id":"A0034F2690114D64915B08EABABF910A","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### Two-Stage model vs. Shifted Lognormal model  \n","\n","与Two-Stage model相比，Shifted Lognormal model具有更高的信度。"]},{"cell_type":"code","execution_count":28,"metadata":{"_id":"841040713C1C446BA0D5C9C697824FF5","collapsed":false,"id":"A8DF7F0AD5A6437A9947A365CA6857A0","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["# 对变量名进行修改\n","def rename_hdi(data):\n","    data = data.reset_index()\n","    data[\"level_1\"] = data[\"level_1\"].replace({'rho_R_mu[0]': 'mu', 'rho_R_sigma[0]': 'sigma'})\n","    return data\n","hdi_logshift = rename_hdi(hdi_logshift)"]},{"cell_type":"code","execution_count":29,"metadata":{"_id":"ABBE09B95EB14405AFA13EA30FF91825","collapsed":false,"id":"6C225FEC8A1C4542A852E8CF2DC6080C","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["#选择mu的重测信度参数进行绘制\n","plot = pd.concat([trad_result, hdi_logshift])\n","plot = plot[plot['level_1'] == 'mu']\n","plot"]},{"cell_type":"code","execution_count":30,"metadata":{"_id":"C16DAA627BC744E9B33C626C02BB4466","collapsed":false,"id":"88574B2514F24D80836966097EB2B3E4","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[],"trusted":true},"outputs":[],"source":["plt.figure(figsize=(6,3), dpi=150)\n","\n","# 计算可信区间\n","ci = [plot['mean'] - plot['hdi_2.5%'], plot['hdi_97.5%'] - plot['mean']]\n","\n","# 通过error bar的形式展现区间和均值\n","plt.errorbar(x=plot['mean'], y=plot['level_0'], xerr=ci,\n","                color='black', capsize=3, linestyle='None', linewidth=1,\n","                marker=\"o\", markersize=5, mfc=\"black\", mec=\"black\")\n","\n","# 调整y轴的刻度使其更集中\n","plt.gca().set_ylim(-0.5, len(plot['level_0']) - 0.5)  # Adjust based on your data\n","\n","# 添加标题\n","plt.xlabel('Test-Retest Correlation', fontsize=8)\n","\n","sns.despine()"]},{"cell_type":"markdown","metadata":{"_id":"517BC30F8DAB4AC0976EEC161789B116","id":"BAD539FAEA284CF293BD9D82910BDCBA","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["## 例3: 贝叶斯推断在认知模型中的应用  \n","\n","在实验数据的收集时，研究者往往会采集个体反应的正确率与反应时。  \n","\n","而传统分析方法并不能同时对两种数据进行分析，从而推断潜在的认知机制。比如，个体是否愿意牺牲更多的反应时间去获得一个更准确的判断。  \n"]},{"cell_type":"markdown","metadata":{"_id":"D31C24AFCFF74BE7A8DBF1D256D45BE5","id":"61CF0BB4B6714466B20296C596953AFD","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["**认知模型能有效的弥补这一问题，比如 drift-diffusion model, DDM ([Pan et al, 2022](https://osf.io/preprints/psyarxiv/6uzga/))。**  \n","\n","\n","![Image Name](https://cdn.kesci.com/upload/sj8vp25j27.jpeg?imageView2/0/w/960/h/960)  \n","\n"]},{"cell_type":"markdown","metadata":{"_id":"72FEDEC424564CB1A286FC7282FDFCFE","id":"714F84E0156B4E3E8CCEE892FD70E54D","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["<center><span style=\"font-size: 68px;\">Part 3: About this course  </span></center>"]},{"cell_type":"markdown","metadata":{"_id":"63B6D06674764A8EB6CB5CB7FFBADBD3","id":"094DD8D26306404AA376A91E16B9E78F","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 2. 课程内容  \n","#### 2.0 课时  \n","9.06 ～ 1.03，18周，十一假期和秋季运动会可能会被放假一次。  \n","\n","#### 2.1 教学目标：  \n","\n","（1）使用Python进行基本的数据处理;  \n","\n","（2）理解贝叶斯推断的基本原理；  \n","\n","（3）了解PyMC3的语法和结构，并能应用于相对简单的情境."]},{"cell_type":"markdown","metadata":{"_id":"5FADE0196F6A49D594379E6FA08FBA48","id":"61285C2C87C64FF7ADA0736DF6F48F1B","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["\n","### 2.2 考核方式：  \n","\n","### 考勤(10%) + 3次小作业 (45%) + 大作业 (45%)   "]},{"cell_type":"markdown","metadata":{"_id":"AC1A2E517AB545C18E01B121824B6B78","id":"636C8F97CF7847DF806CE98DAD9A66A0","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["#### 大作业  \n","\n","大作业要求  \n","\n","* 真实的数据分析，数据来源：  \n","  * Science: https://www.science.org/  \n","  * Science advances: https://www.science.org/journal/sciadv  \n","  * Nature: https://www.nature.com/  \n","  * Nature human behaviour：https://www.nature.com/nathumbehav/  \n","  * Nature communications: https://www.nature.com/ncomms/  \n","  * Psychological Science: https://journals.sagepub.com/home/pss  \n","  * Cognition: https://www.sciencedirect.com/journal/cognition  \n","  * Collabra: Psychology: https://online.ucpress.edu/collabra  \n","* 合作完成 (每个小组3-5人, 可自行组队或随机分配)  \n","\n","大作业提交内容  \n","\n","* 代码 (对公开数据进行完整分析的代码，使用贝叶斯统计方法，具有可重复性，有注释和文档说明)  \n","\t* 如果原文章使用非贝叶斯方法，可以考虑先重复原文档的分析，再进行贝叶斯分析。  \n","* 与文字报告 (包括标题，摘要，研究背景或研究问题，研究方法，分析结果，结论六个主要部分)  \n","* 进行汇报 (使用 PPT 汇报对研究问题和代码的分析过程进行汇报)  \n","\n","大作业评分标准  \n","* 分工合理、数据分析流程完整、汇报展示清晰美观"]},{"cell_type":"markdown","metadata":{"_id":"56659BCC66C84D71920DB92500DC4D90","id":"2A78D831E7BD4E7A9D3C4C5563434498","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["\n","### 2.3 课程风格：  \n","\t（1）内容有挑战、考核不复杂  \n","\t（2）1/3一节课展示或互动抄代码  \n","\t（3）专门设有答疑时间，助教给大家答疑解惑  \n","\n","\n"]},{"cell_type":"markdown","metadata":{"_id":"C4F671D90CD142F5A157D00B8F29EEAC","id":"FB1FB8A3D7294EA8B80AFCA390179FB5","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["\n","### 2.4 课程大纲  \n","### Intro  \n","1: 课程介绍（为什么要用贝叶斯/PyMC3，展示一个贝叶斯因子和贝叶斯层级模型例子，课程安排）  \n","\n","### I Basics：  \n","2: 贝叶斯公式  \n","* 单一事件的贝叶斯模型(先验、似然、分母和后验)  \n","* 随机变量的贝叶斯模型(先验、似然、分母和后验)  \n","\n","3: 建立一个完成的贝叶斯模型：Beta-Binomial model  \n","* Beta先验  \n","* Binomial与似然  \n","* Beta-Binomial model  \n","\n","4: 贝叶斯模型的特点：数据-先验与动态更新  \n","* 先验与数据对后验的影响  \n","* 数据顺序不影响后验  \n","\n","5: 经典的贝叶斯模型：Conjugate families  \n","* Gamma-Poisson  \n","* Normal-Normal  \n","\n","### II 近似后验估计  \n","6: 近似后验的方法  \n","* 网格法  \n","* MCMC  \n","\n","7: 深入一种MCMC算法  \n","* M-H 算法  \n","\n","8: 基于后验的推断  \n","* 后验估计  \n","* 假设检验  \n","* 后验预没  \n","\n","### III Bayesian回归模型  \n","9: 简单的Bayesian线性回归模型  \n","* 建立模型  \n","* 调整先验  \n","* 近似后验  \n","* 基于近似后验的推断  \n","* 序列分析  \n","\n","10: 对回归模型的评估  \n","* 评估模型的标准  \n","* 对简单线性模型的估计  \n","  \n","11: 扩展的线性模型  \n","* 多自变量的线性回归  \n","\n","12: GLM: Bayes factors  \n","\n","13: GLM: Logistic Regression  \n","\n","14: Hierachical Bayesian Model 1  \n","\n","15: Hierachical Bayesian Model 2"]},{"cell_type":"markdown","metadata":{"_id":"03F3F2DD1C59449EAFC006363FCC4CAC","id":"13694EB3E2A94E229C45E965A300C61E","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 2.5 参考书  \n","\n","#### 1. 英文教材：  \n","\n","![Image Name](https://cdn.kesci.com/upload/sj8izbv81l.png?imageView2/0/w/960/h/960)  \n","\n","\n","#### 2. 中文教材：  \n","\n","![Image Name](https://cdn.kesci.com/upload/sj8iytode2.png?imageView2/0/w/320/h/320)  \n"]},{"cell_type":"markdown","metadata":{"_id":"C7D52EC5C915446CA8C8BBFF49C39D94","id":"90E8AC89754E44BA8F9CD5D2DAE73CD7","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["\n","![Image Name](https://www.eva.mpg.de/fileadmin/content_files/staff/richard_mcelreath/images/richard_dec_2023.png)  \n","\n","Prof. Richard McElreath"]},{"cell_type":"markdown","metadata":{"_id":"8B5F9CE0D87C47658E6A55FE9D6600F8","id":"381A1814CC6841B190C788000669FFCD","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["### 2.6 课程好帮手（AI工具）  \n","\n","- 如果你有问题，除了可以向老师和助教寻求帮助，还可以使用AI工具。  \n","- 这款工具是为贝叶斯课程特别定制的，免费且无需翻墙。  \n","\n","<p align=\"center\">  \n","  <img src=\"https://cdn.kesci.com/upload/sj6zpgijv9.jpeg?imageView2/0/w/960/h/960\" alt=\"Image Name\" />  \n","</p>"]},{"cell_type":"markdown","metadata":{"_id":"95906B7445D74F2C857A3BCBDDE5A2D6","id":"35066EDF697041B39DE703D7274F9516","jupyter":{},"notebookId":"66d83816136d01cc20208d4c","runtime":{"execution_status":null,"is_visible":false,"status":"default"},"scrolled":false,"slideshow":{"slide_type":"slide"},"tags":[]},"source":["<center><span style=\"font-size: 68px;\">THANK YOU  </span></center>"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.5.2"}},"nbformat":4,"nbformat_minor":2}
